package org.openems;

import java.util.Iterator;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.openems.meta.BookmarkModelMeta;
import org.openems.meta.ParameterModelMeta;
import org.openems.model.BookmarkModel;
import org.openems.model.ParameterModel;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Key;

@Path("/bookmark")
public class BookmarkResource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public BookmarkEntities get(@QueryParam("productName") String productName) {
        String email = Utility.getEmail();
        
        BookmarkModelMeta e = BookmarkModelMeta.get();
        Iterator<BookmarkModel> it = Datastore.query(e).filter(e.userEmail.equal(email)).filter(e.productName.equal(productName)).asIterator();
    
        BookmarkEntities ret = new BookmarkEntities();
        while(it.hasNext()) {
            BookmarkModel model = it.next();
            BookmarkEntity entity = new BookmarkEntity();
            entity.bookmarkName = model.getBookmarkName();
            entity.productName = model.getProductName();
            
           ret.entities.add(entity);
        }
        
        return ret;
    }
    
    @POST
    public String post(String text) {
        return null;
    }
    
    @PUT
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.TEXT_PLAIN)
    public String put(BookmarkEntity entity) {
        String email = Utility.getEmail();
        
        BookmarkModelMeta ee = BookmarkModelMeta.get();
        if (Datastore.query(ee).filter(ee.bookmarkName.equal(entity.bookmarkName)).asList().size() == 0) {
            BookmarkModel model = new BookmarkModel();
            model.setBookmarkName(entity.bookmarkName);
            model.setUserEmail(email);
            model.setProductName(entity.productName);
            Datastore.put(model);
            
            ParameterModelMeta e = ParameterModelMeta.get();
            List<ParameterModel> list = Datastore.query(e).filter(e.productName.equal(entity.productName)).filter(e.userEmail.equal(email)).asList();
            for (ParameterModel parameter : list) {
                Key key = Datastore.allocateId(ParameterModel.class);
                parameter.setKey(key);
                parameter.setBookMark(model.getKey());
                parameter.setLatest(false);
                Datastore.put(parameter);
            }
        }
        return "OK";
    }
    
    @DELETE
    public String delete(String text) {
        return null;
    }
}
